<template>
  <div align="center">
      <el-form ref="form1" :model="form1"  :rules="rules" :inline="true">
        <el-form-item  label="选择目录" prop="bindCataId" >
          <el-cascader
            v-model="form1.bindCataId"
            :options="cataOptions"
            @change="handleChange" ></el-cascader>
        </el-form-item>
      </el-form>
  </div>
</template>

<script>
import {listCata} from "@/api/market/cata";

export default {
  name: 'DataApiEdit',
  components: {

  },
  props: {
    data: {
      type: Object,
      default: function() {
        return {}
      }
    }
  },
  data() {
    return {
      title: '数据API编辑',
      cataOptions: [],
      // 表单参数
      form1: {
        bindCataId: undefined
      },
      // 表单校验
      rules: {
        bindCataId: [
          { required: true, message: '绑定目录不能为空', trigger: 'blur' }
        ]
      },
    }
  },
  created() {
    this.getList()
  },
  mounted() {
  },
  methods: {
    /** 查询目录列表 */
    getList() {
      // this.loading = true
      listCata().then(response => {
        const { data } = response
        const cataList = data
        // 插件转tree
        this.cataOptions = this.handleIndustryData(cataList)
        // this.loading = false
      })
    },
    handleChange(value) {
      console.log(value);
    },
    handleIndustryData(src){
      const id =  'id'
      const parentId = 'parentId'
      const idMap = {}
      const parentList = {}
      src.forEach(v => { idMap[v[id]] = {label: v.cataName,
        value: v.id}
        const parent = v[parentId]
        if(parent > 0 ) {
          parentList[parent] = parent
        }
      })
      let dest = []
      // let pids = Object.keys(src.parentId)
      let labels = []
      src.forEach(v => {
        if(parentList[v.id]){
          labels.push(v)
          delete idMap[v.id]
        }
      })
      dest = labels.map((item, index) => {
        console.log(index)
        return {
          value: item.id,
          label: item.cataName,
        }
      })

      let childrens = []
      for(let i = 0; i < dest.length; i++){
        let tempChild = src.filter((item) => {
          return item.parentId == dest[i].value
        })
        let child = tempChild.map((item) => {
          return {
            label: item.cataName,
            value: item.id
          }
        })
        childrens.push(child)
      }

      let newData = dest.map((item, index) => {
        return {
          ...item,
          children: childrens[index]};
      })
      return newData
    }
  }
}
</script>

<style lang="scss" scoped>
.el-card ::v-deep .el-card__body {
  height: calc(100vh - 230px);
  overflow-y: auto;
}
</style>
